<?php
/*********************************************
  CPG Dragonfly™ CMS
  ********************************************
  Copyright © 2004 - 2007 by CPG-Nuke Dev Team
  http://dragonflycms.org

  Dragonfly is released under the terms and conditions
  of the GNU GPL version 2 or any later version
**********************************************/
if (!defined('CPG_NUKE')) { exit; }

class Dragonfly_Admin_Menu
{
	const
		GRAPH =  1,
		BLOCK =  2,
		CSS   =  4,
		JS    =  8,
		TABS  = 16;

	static private
		$items;

	# Constructor
	static private function init()
	{
		global $cpgtpl;
		$adlinks = Dragonfly::getKernel()->CACHE->get('Dragonfly_Admin_Menu_Links');
		if (!$adlinks) {
			$adlinks = array();

			$linksdir = dir('admin/links');
			while ($file = $linksdir->read()) {
				# CPG-Nuke system							 PHP-Nuke system
				if (preg_match('/^adlnk_.*?\.php$/', $file) || preg_match('/^links\..*?\.php$/', $file)) {
					$adlinks[] = 'admin/links/'.$file;
				}
			}
			$linksdir->close();

			$adlinks += Dragonfly_Modules::ls('admin/adlinks.inc', false);
			Dragonfly::getKernel()->CACHE->set('Dragonfly_Admin_Menu_Links', $adlinks);
		}
		$menuitems = array();
		foreach ($adlinks as $module => $path) {
			if (is_file($path)) include($path);
		}
		self::$items = is_array($menuitems) ? $menuitems : array();
		self::$items[_ADMIN][_MENU]['URL'] = DOMAIN_ADMIN;
		self::$items[_ADMIN][_MENU]['IMG'] = '';
		self::$items[_ADMIN][_ADMINLOGOUT]['URL'] = URL::admin('logout');
		self::$items[_ADMIN][_ADMINLOGOUT]['IMG'] = '';
		ksort(self::$items);

		$cpgtpl->assign_vars(array(
			'S_ADMIN_GRAPHMENU' => false,
			'S_ADMIN_CSSMENU'   => false,
			'S_ADMIN_JSMENU'    => false,
			'S_ADMIN_TABSMENU'  => false
		));
	}

	static public function display($viscat='all', $type)
	{
		global $cpgtpl, $MAIN_CFG, $op;
		if (is_null(self::$items)) {
			self::init();
		}

		$uri = str_replace('&', '&amp;', URL::query());

		# Small images only block
		if ('blockgfx' === $type)
		{
			$content = '';
			foreach (self::$items as $cat => $action_array) {
				ksort($action_array);
				while (list($title, $info) = each($action_array)) {
					$img = self::addGraphItem($info['IMG'], isset($info['MOD'])?$info['MOD']:'', '48x48');
					if (!empty($img)) {
						$content .= '<a href="'.$info['URL'].'"><img src="'.DF_STATIC_DOMAIN.$img."\" border=\"0\" alt=\"\" title=\"$title\" width=\"25\" /></a>\n";
					}
				}
			}
			return $content;
		}

		$type = (int) $type;
		$uri = str_replace('&', '&amp;', URL::query());

		# Sideblock
		if (self::BLOCK & $type && self::BLOCK & $MAIN_CFG->global->admingraphic)
		{
			$content = '';
			foreach (self::$items as $cat => $action_array)
			{
				$content .= '<strong>'.(defined($cat) ? constant($cat) : $cat).'</strong><div style="margin-left: 8px;">';
				ksort($action_array);
				while (list($action, $info) = each($action_array))
				{
					$op_url = explode(DOMAIN_ADMIN.'&amp;op=', $info['URL']);
					$content .= ($uri == $info['URL'] || (isset($op_url[1]) && $op_url[1] == $op) ? '<a href="'.$info['URL'].'"><strong>'.$action.'</strong></a>' : '<a href="'.$info['URL'].'">'.$action.'</a>').'<br />';
				}
				$content .= '</div>';
			}
			$block = array(
				'bid' => 9999,
				'view' => 2,
				'side' => 'r',
				'title' => _ADMINMENU,
				'content' => $content
			);
			Blocks::custom($block);
		}

		# Big graphical menu
		if (self::GRAPH & $type && self::GRAPH & $MAIN_CFG->global->admingraphic)
		{
			$cpgtpl->assign_var('S_ADMIN_GRAPHMENU', true);
			if (defined('ADMIN_PAGES') && DOMAIN_ADMIN != $uri && 'all' == $viscat) {
				global $op;
				foreach (self::$items as $cat => $action_array) {
					while (list(, $info) = each($action_array)) {
						if ($uri == $info['URL']) {
							$viscat = $cat;
							break;
						} else if (0 === strpos($uri, $info['URL'])) {
							$viscat = $cat;
						}
					}
				}
			}
			foreach (self::$items as $cat => $action_array)
			{
				if ($cat == _ADMIN) { continue; }
				if ($viscat == 'all' || $viscat == $cat) {
					$cattitle = defined($cat) ? constant($cat) : $cat;
					$cpgtpl->assign_block_vars('menucat', array('TITLE' => $cattitle));
					ksort($action_array);
					while (list($title, $info) = each($action_array))
					{
						$img = self::addGraphItem($info['IMG'], isset($info['MOD'])?$info['MOD']:'', '48x48');
						if (!empty($img)) { $img = '<img src="'.$img.'" border="0" alt="'.$title.'" title="'.$title.'" />'; }
						$cpgtpl->assign_block_vars('menucat.menuitem', array(
							'TITLE'	=> $title,
							'IMAGE'	=> $img,
							'U_OPTION' => $info['URL']
						));
					}
				}
			}
		}

		# CSS menu
		elseif (self::CSS & $type && self::CSS & $MAIN_CFG->global->admingraphic)
		{
			if (defined('ADMIN_PAGES')) {
				$content = '';
			} else {
				$content = '<ul>';
			}
			global $db, $prefix, $mainindex;
			foreach (self::$items as $cat => $action_array)
			{
				$cat = defined($cat) ? constant($cat) : $cat;
				if (defined('ADMIN_PAGES')) {
					$content .= "\n <li><a><b>&#8226;</b> $cat</a><ul>";
				} else {
					$content .= "\n <li><span>&raquo;</span><a class=\"submenu\">$cat</a><ul>";
				}
 				ksort($action_array);
				foreach ($action_array as $title => $info)
				{
					$img = self::addGraphItem($info['IMG'], (isset($info['MOD'])?$info['MOD']:''), '12x12');
					if (!empty($img)) { $img = " style=\"background: url($img) no-repeat left; height:12px; width:12px;\""; }
					if (!empty($info['SUB'])) {
						$content .= "\n  <li><span$img>&nbsp;</span><a class=\"submenu\" href=\"".$info['URL']."\">$title</a><ul>";
						foreach ($info['SUB'] as $subtitle => $subinfo) {
							$content .= "\n   <li><span$img>&nbsp;</span><a href=\"$subinfo\">$subtitle</a></li>";
						}
						$content .= "\n  </ul></li>";
					} else {
						$content .= "\n  <li><span$img>&nbsp;</span><a href=\"".$info['URL']."\">$title</a></li>";
					}
				}
				$content .= "\n </ul></li>";
			}
			if (defined('ADMIN_PAGES')) {
				$content .= '';
			} else {
				$content .= "\n</ul>\n";
			}
			$cpgtpl->assign_var('S_ADMIN_CSSMENU', $content); # here till templated
		}

		# JavaScript menu
		else if (self::JS & $type && self::JS & $MAIN_CFG->global->admingraphic)
		{
			global $db, $prefix, $mainindex, $CPG_SESS;
			$content = "var adminMenu = [\n[null, '".str_replace('\'', '\\\'', _HOME)."' , '$mainindex', null, null,";

			# Load active modules from database
			$sql = '(SELECT	m.title as link, m.custom_title as title, m.view, m.active, m.inmenu, m.cat_id, c.name, c.image, c.pos AS catpos, c.link AS catlnk, c.link_type AS cattype FROM '.$prefix.'_modules AS m LEFT JOIN '.$prefix.'_modules_cat c ON (c.cid = m.cat_id))
			 UNION (SELECT l.link as link, l.title, l.view, l.active, l.active as inmenu, l.cat_id, c.name, c.image, c.pos AS catpos, c.link AS catlnk, c.link_type AS cattype FROM '.$prefix.'_modules_links AS l LEFT JOIN '.$prefix.'_modules_cat c ON (c.cid = l.cat_id))';
			$result = $db->sql_query($sql);
			while ($row = $db->sql_fetchrow($result))
			{
				if (empty($row['title'])) $row['title'] = $row['link'];
				$row['title'] = defined("_$row[link]LANG") ? constant("_$row[link]LANG") : str_replace('_', ' ', $row['title']);
				$row['title'] = str_replace('\'', '\\\'', $row['title']);
				if (!isset($row['catpos'])) $row['catpos'] = -1;
				$menucats[$row['catpos']][$row['title']] = $row;
			}
			$result->free();
			ksort($menucats);
			# Process the active modules
			while (list($cat, $items) = each($menucats))
			{
				ksort($items);
				$catcontent = $catimage = $tmpcontent = '';
				while (list($dummy, $item) = each($items))
				{
					$image = 'icon_unselect.gif';
					if (!$item['active']) $image = 'icon_cantselect.gif';
					elseif ($item['active'] && !$item['inmenu']) $image = 'icon_hideselect.gif';
					$image = isset($item['lnkimage']) ? $item['lnkimage'] : $image;
					$tmpcontent .= "\n    ['<img src=\"".Menu::mmimage($image)."\" />', '$item[title]', '".URL::index($item['link'])."', null, null],";
					$catimage = $item['image'];
					$cattitle = $item['name'];
					$catlnk   = (false === strpos($item['catlnk'], '.') ? URL::index($item['catlnk']) : $item['catlnk']);
				}
				$cattitle = defined($cattitle) ? constant($cattitle) : $cattitle;
				if ($cat >= 0) {
					$content .= "\n ['<img src=\"".Menu::mmimage($catimage)."\" width=\"16px\" height=\"16px\" alt=\"\" />', '".str_replace('\'', '\\\'', $cattitle)."', '$catlnk', null, null,".substr($tmpcontent,0,-1)."\n ],";
				} else {
					$content .= "\n  [null, 'No category', null, null, null,".substr($tmpcontent,0,-1)."\n  ],";
				}
			}
			$content = substr($content,0,-1)."\n],";

			# Process the admin links
			foreach (self::$items as $cat => $action_array)
			{
				$cat = defined($cat) ? constant($cat) : $cat;
				$cat = str_replace('\'', '\\\'', $cat);
				$content .= "\n[null, '$cat', null, null, null,";
				ksort($action_array);
				foreach ($action_array as $title => $info)
				{
					$img = self::addGraphItem($info['IMG'], isset($info['MOD'])?$info['MOD']:'', '48x48');
					$img = empty($img) ? 'null' : "'<img src=\"$img\" width=\"16px\" height=\"16px\" alt=\"\" />'";
					$content .= "\n  [$img, '".str_replace('\'', '\\\'', $title)."', '".str_replace('&amp;', '&', $info['URL'])."', null, null";
					if (isset($info['SUB'])) {
						$content .= ',';
						foreach ($info['SUB'] as $subtitle => $subinfo) {
							$content .= "\n	['', '".str_replace('\'', '\\\'', $subtitle)."', '".str_replace('&amp;', '&', $subinfo)."', null, null],";
						}
						$content = substr($content,0,-1)."\n  ],";
					} else {
						$content .= '],';
					}
				}
				$content = substr($content,0,-1)."\n],";
			}
			$cpgtpl->assign_var('S_ADMIN_JSMENU', substr($content,0,-1)."\n];\n"); # here till templated
		}

		# Tabbed
		else if (self::TABS & $type && self::TABS & $MAIN_CFG->global->admingraphic)
		{
			$cpgtpl->assign_var('S_ADMIN_TABSMENU', true);
			foreach (self::$items as $cat => $action_array)
			{
				if ($cat == _ADMIN) { continue; }

				$items = array();
				$current = false;
				ksort($action_array);
				foreach ($action_array as $title => $info)
				{
					$img = self::addGraphItem($info['IMG'], isset($info['MOD'])?$info['MOD']:'', '48x48');
					$items[] = array(
						'TITLE'	=> $title,
						'IMAGE'	=> $img,
						'U_OPTION' => $info['URL']
					);
					$current |= (false !== strpos($_SERVER['REQUEST_URI'],htmlspecialchars_decode($info['URL'])));
				}
				if ($items)
				{
					$cpgtpl->assign_block_vars('menucat', array(
						'TITLE' => defined($cat) ? constant($cat) : $cat,
						'CLASS' => $current?'current':''
					));
					foreach ($items as $item) {
						$cpgtpl->assign_block_vars('menucat.menuitem', $item);
					}
				}
			}
		}
	}

	static private function addGraphItem($image, $module, $size='12x12')
	{
		global $CPG_SESS;

		$theme = Dragonfly::getKernel()->OUT->tpl_name;
		if (!$theme) $theme = $CPG_SESS['theme'];

		if (false !== strpos($image, './') || empty($image)) $image = 'not-found';

		$image = "/admin/$size/$image";

		if (isset($CPG_SESS['menu_img'][$theme][$image])) {
			$img = $CPG_SESS['menu_img'][$theme][$image];
		} else {
			$paths = array("themes/{$theme}/images", 'themes/default/images');
			if (!empty($module)) array_push($paths, "modules/{$module}/images");

			foreach ($paths as $path)
			{
				# Search PNG and GIF in different location
				if (file_exists($path.$image.'.png')) {
					$img = $path.$image.'.png';
				}
				else if (file_exists($path.$image.'gif')) {
					$img = $path.$image.'.gif'; # .gif images support to be dropped
				}
			}
		}
		if (empty($img)) {
			$img = notify_image();
		}

		$CPG_SESS['menu_img'][$theme][$image] = $img;
		return DF_STATIC_DOMAIN .$img;
	}

}
